<?php

namespace app\logic\fp;

use app\common\library\SnowFlake;
use app\common\model\fp\PostComments;
use app\logic\BaseLogic;
use RuntimeException;

class PostCommentLogic extends BaseLogic
{

    /**
     * 查询评论数量
     * @param $postId
     * @return int
     * @throws \Throwable
     */
    public static function getCommentCount($postId): int
    {
        return PostComments::initModel($postId)->where('post_id', $postId)->count();
    }

    /**
     * 评论
     * @param $params
     * @return mixed
     * @throws \Throwable
     */
    public function comment($params)
    {
        if (!PostUnlockedLogic::getInstance()->isUnlockedByPost($params['comment_user_id'], $params['post_id'])) {
            throw new RuntimeException(__('Dynamic not unlocked, unable to comment'));
        }
        $model = PostComments::initModel($params['post_id']);
        $reply_user_id = 0;
        if ($params['parent_id']) {
            $comment = PostComments::initModel($params['post_id'])->where('id', $params['parent_id'])->find();
            if (!$comment) {
                throw new RuntimeException(__('Comment not found'));
            }
            if ($comment['comment_user_id'] != $params['reply_user_id']) {
                throw new RuntimeException(__('You can only reply to your own comments'));
            }
        }

        $data = [
            'comment_user_id' => $params['comment_user_id'],
            'parent_id' => $params['parent_id'] ?: 0,
            'reply_user_id' => $reply_user_id,
            'post_user_id' => $params['creator_id'],
            'post_id' => $params['post_id'],
            'content' => $params['content'],
            'create_time' => time(),
        ];
        $model->save($data);

        return $model->toArray();
    }

    /**
     * @param string $postId 动态id
     * @param string $userId 当前登录者id
     * @return array
     * @throws \Throwable
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function list(string $postId, string $userId)
    {
        $postInfo = PostComments::initModel($postId)->where('post_id', $postId)->field('post_id,post_user_id')->find();

        if (!$postInfo) {
            return [];
        }

        $creatorId = $postInfo['post_user_id'];
        $post = \app\common\model\fp\Post::initModel($postInfo['post_user_id'])->where('id', $postId)->find();

        if (!$post) {
            return [];
        }

        // 初始化模型
        $model = PostComments::initModel($postId)->order('create_time desc');

        // 不是作者的时候只能查看自己的
        if ($creatorId != $userId) {
            $list = $model->where(function ($query) use ($userId) {
                $query->where('comment_user_id', '=', $userId)
                    ->whereOr('reply_user_id', '=', $userId);
            })->whereOr(function ($query) use ($creatorId) {
                $query->where('comment_user_id', '=', $creatorId)
                    ->whereOr('parent_id', '=', 0);
            })->where('post_id', '=', $postId)
                ->order('create_time desc')
                ->select()->toArray();

        } else {
            $list = $model->where('post_id', '=', $postId)->select()->toArray();
        }

        $comment_user_ids = array_column($list, 'comment_user_id');
        $reply_user_ids = array_column($list, 'reply_user_id');
        $userIds = array_unique(array_merge($comment_user_ids, $reply_user_ids));
        $userList = \app\common\model\User::initModel()
            ->where('id', 'in', $userIds)
            ->field('id,nickname,avatar')
            ->select()
            ->toArray();
        $userList = array_column($userList, null, 'id');

        $data = [];
        foreach ($list as $item) {
            $item['comment_user_info'] = $userList[$item['comment_user_id']] ?? [];
            $item['reply_user_info'] = $userList[$item['reply_user_id']] ?? [];
            $item['child'] = [];
            if ($item['parent_id'] == 0) {
                $temp = $data[$item['id']] ?? [];
                $data[$item['id']] = array_merge($temp, $item);
            } else {
                $data[$item['parent_id']]['child'][] = $item;
            }
        }

        foreach ($data as &$item) {
            if (!empty($item['child'])) {
                // 子数组按 create_time 升序排序
                usort($item['child'], function ($a, $b) {
                    return $a['create_time'] <=> $b['create_time'];
                });
            } else {
                $item['child'] = [];
            }
        }

        // 最外层数组按 create_time 降序排序
        usort($data, function ($a, $b) {
            return $b['create_time'] <=> $a['create_time'];
        });

        return array_values($data);
    }

}